import { useAppDispatch, useAppSelector } from 'modules/store';
import { selectAddressList, getList, clearPageState } from 'modules/address/list';
import React, { memo, useEffect, useState, useRef } from 'react';
import { SearchIcon } from 'tdesign-icons-react';
import type { DialogProps, TableProps } from 'tdesign-react';
import { Button, Col, Dialog, Input, Row, Table, MessagePlugin } from 'tdesign-react';
import Style from './addressBook.module.less';
import CloseIcon from 'assets/icons/close.svg?component';
import request from '../../utils/request';
import { amapAddressToMyAddress, randomKey, amapPromise } from 'utils/common';

export default memo(
  (props: {
    visible?: boolean;
    setVisible: (value: Boolean) => void;
    setAddress: (item: any, index: number) => void;
  }) => {
    // const [visible, setVisible] = useState(false);
    const onConfirm: DialogProps['onConfirm'] = (context) => {
      console.log('点击了确认按钮', context);
      // props.setVisible(false);
    };
    const onCancelDialog: DialogProps['onCancel'] = (context) => {
      console.log('点击了取消按钮', context);
    };
    const onClickCloseBtn: DialogProps['onCloseBtnClick'] = (context) => {
      console.log('点击了关闭按钮', context);
    };
    const onKeydownEsc: DialogProps['onEscKeydown'] = (context) => {
      console.log('按下了ESC', context);
    };
    const onClickOverlay: DialogProps['onOverlayClick'] = (context) => {
      console.log('点击了蒙层', context);
    };
    const handleClose: DialogProps['onClose'] = (context) => {
      console.log('关闭弹窗，点击关闭按钮、按下ESC、点击蒙层等触发', context);
      props.setVisible(false);
    };

    const dispatch = useAppDispatch();
    const pageState = useAppSelector(selectAddressList);
    const [selectedRowKeys, setSelectedRowKeys] = useState<(string | number)[]>([1, 2]);
    const { loading, addressList, page_num, page_size, total } = pageState;
    const [isEditing, setIsEditing] = useState<boolean>(false);

    const tableRef = useRef(null);
    const [editableRowKeys, setEditableRowKeys] = useState([]);
    const [addressEditList, setAddressEditList] = useState<any[]>([]);
    let currentSaveId = '';
    // 保存变化过的行信息
    const [editMap, setEditMap] = useState({});
    const onEdit = (e) => {
      const { id } = e.currentTarget.dataset;
      // 如果rowKey本身是number类型，在这里进行number转换,保证功能正常
      // id = Number(id);
      if (!editableRowKeys.includes(id)) {
        setAddressEditList([...addressList]);
        setIsEditing(true);
        setEditableRowKeys(editableRowKeys.concat(id));
      }
    };

    // 更新 editableRowKeys
    const updateEditState = (id: string) => {
      const index = editableRowKeys.findIndex((t) => t === id);
      editableRowKeys.splice(index, 1);
      setEditableRowKeys([...editableRowKeys]);
    };

    const onCancel = (e) => {
      console.log('cancel');
      const { id } = e.currentTarget.dataset;
      console.log(id);
      // 如果rowKey本身是number类型，在这里进行number转换,保证功能正常
      // id = Number(id);

      updateEditState(id);
      tableRef.current.clearValidateData();
      if (id.startsWith('new')) {
        addressEditList.shift();
        setAddressEditList([...addressEditList]);
      }
      setIsEditing(false);
    };

    const onUse = (row) => {
      console.log('current11: ', row);
      props.setAddress(row);
      props.setVisible(false);
    };
    const onDelete = (row) => {
      const { id } = row;
      request.post('/api/v1/address/delete', { id }).then((res) => {
        if (res?.code === 'OK') {
          dispatch(
            getList({
              page_size: pageState.page_size,
              page_num: pageState.page_num,
            }),
          );
          MessagePlugin.success('删除成功');
        }
      });
    };

    const onSave = (e) => {
      const { id } = e.currentTarget.dataset;
      console.log(id, e.currentTarget);
      // 如果rowKey本身是number类型，在这里进行number转换,保证功能正常
      // id = Number(id);
      currentSaveId = id;
      console.log('editMap:', editMap);
      // 触发内部校验，可异步接收校验结果，也可在 onRowValidate 中接收异步校验结果
      tableRef.current.validateRowData(id).then((params) => {
        console.log('Promise Row Validate:', params, editMap);
        if (params.result.length) {
          const r = params.result[0];
          MessagePlugin.error(`${r.col.title} ${r.errorList[0].message}`);
          return;
        }
        // 如果是 table 的父组件主动触发校验
        if (params.trigger === 'parent' && !params.result.length) {
          const current = editMap[currentSaveId];
          console.log('current: ', current);
          // 单行数据校验：校验通过再保存数据
          if (current) {
            const full_address = current.editedRow.full_address;
            amapPromise.then((AMap) => {
              const autoOptions = {
                city: '全国',
              };
              const autoComplete = new AMap.AutoComplete(autoOptions);
              autoComplete.search(full_address, (status, result) => {
                // 搜索成功时，result即是对应的匹配数据
                console.log(status, result);
                const tips = result?.tips || [];
                console.log('tips: ', tips);
                if (tips.length > 1) {
                  // 取第一个，设置addresses[0]
                  // 省 市 区 街道 姓名 电话 经纬度 详细地址
                  current.editedRow = { ...current.editedRow, ...amapAddressToMyAddress(tips[0].id ? tips[0] : tips[1]) };
                  if (currentSaveId.startsWith('new_')) {
                    console.log('current.editedRow:', current.editedRow);
                    // 新增
                    const param = { ...current.editedRow };
                    delete param.id;
                    request.post('/api/v1/address/add', param).then((res) => {
                      console.log(res);
                      // addressList.splice(current.rowIndex, 1, current.editedRow);
                      // setAddressEditList([...addressList]);
                      // MessagePlugin.success('保存成功');
                      dispatch(
                        getList({
                          page_size: pageState.page_size,
                          page_num: pageState.page_num,
                        }),
                      );
                      setIsEditing(false);
                    });
                  } else {
                    // 修改
                    const param = { ...current.editedRow };
                    request.post('/api/v1/address/update', param).then((res) => {
                      console.log(res);
                      dispatch(
                        getList({
                          page_size: pageState.page_size,
                          page_num: pageState.page_num,
                        }),
                      );
                      setIsEditing(false);
                    });
                  }
                  console.log('787:', current.editedRow);
                }
              });
            });
          }
          updateEditState(currentSaveId);
        }
      });
    };

    const onRowValidate: TableProps['onRowValidate'] = (params) => {
      console.log('Event Row Validate:', params);
    };

    // 行数据编辑时触发，返回最新输入结果
    const onRowEdit: TableProps['onRowEdit'] = (params) => {
      console.log('edit', params, addressList);
      const { row, rowIndex, col, value } = params;
      const oldRowData = editMap[row.id]?.editedRow || row;
      const editedRow = { ...oldRowData, [col.colKey]: value };
      editMap[row.id] = {
        ...params,
        editedRow,
      };
      setEditMap({ ...editMap });
      console.log('xxxx:editMap: ', editMap);
      addressEditList.splice(rowIndex, 1, editedRow);
      setAddressEditList([...addressEditList]);
    };
    function getAddressList() {
      request
        .post('/api/v1/address/list', {
          address_type: '卸货地址',
          page_size: 10,
          page_num: 1,
          sort_type: 'frequency',
          asc: false,
        })
        .then((res) => {
          setAddressEditList(res.data || []);
        });
    }

    useEffect(() => {
      // console.log(props.visible, 'visible');
      // if props.visible, get data
      if (props.visible) {
        dispatch(
          getList({
            address_type: '卸货地址',
            sort_type: 'frequency',
            asc: false,
            page_size: pageState.page_size,
            page_num: pageState.page_num,
          }),
        );
        return () => {
          dispatch(clearPageState());
        };
      }
    }, [props.visible]);

    function addAddress() {
      const id = `new_${randomKey()}`;
      const editAddressList = [...addressList];
      editAddressList.unshift({
        id: id,
        full_address: '',
        province: '',
        city: '',
        district: '',
        subArea: '',
        location: '',
        name: '',
        phone: '',
        address_type: '卸货地址',
        warehouse_name: '',
        remark: '',
      });
      setAddressEditList([...editAddressList]);
      setIsEditing(true);
      setEditableRowKeys(editableRowKeys.concat(id));
    }
    useEffect(() => {}, []);

    function onSelectChange(value: (string | number)[]) {
      setSelectedRowKeys(value);
    }
    // serial-number,address,short_address,extra,name,phone,op
    return (
      <Dialog
        className={Style.addressBookDialog}
        header='地址簿'
        visible={props.visible}
        confirmOnEnter
        onClose={handleClose}
        onConfirm={onConfirm}
        confirmBtn={null}
        onCancel={onCancelDialog}
        cancelBtn={null}
        onEscKeydown={onKeydownEsc}
        onCloseBtnClick={onClickCloseBtn}
        onOverlayClick={onClickOverlay}
        footer={false}
        width={'90%'}
        closeBtn={<CloseIcon />}
      >
        <Row justify='space-between' className={Style.toolBar}>
          <Col>
            <Input prefixIcon={<SearchIcon />} placeholder='搜索地址/姓名电话' />
          </Col>
          <Col>
            <Row gutter={8} align='middle'>
              <Col>
                <Button variant='outline' theme='default' onClick={addAddress}>
                  新增地址
                </Button>
              </Col>
              {/* <Col> */}
              {/*   <div>已选 {selectedRowKeys?.length || 0} 项</div> */}
              {/* </Col> */}
            </Row>
          </Col>
        </Row>

        <Table
          columns={[
            // {
            //   colKey: 'row-select',
            //   fixed: 'left',
            //   type: 'multiple',
            //   // width: 50,
            // },
            { colKey: 'serial-number', title: '序号', fixed: 'left' },
            {
              align: 'left',
              width: 200,
              ellipsis: true,
              colKey: 'full_address',
              title: '地址',
              edit: {
                // 1. 支持任意组件。需保证组件包含 `value` 和 `onChange` 两个属性，且 onChange 的第一个参数值为 new value。
                // 2. 如果希望支持校验，组件还需包含 `status` 和 `tips` 属性。具体 API 含义参考 Input 组件
                component: Input,
                // props, 透传全部属性到 Input 组件
                props: {
                  // clearable: true,
                  autofocus: true,
                  size: 'large',
                },
                // 校验规则，此处同 Form 表单
                rules: [{ required: true, message: '不能为空' }],
                showEditIcon: false,
              },
            },

            {
              align: 'left',
              width: 200,
              ellipsis: true,
              colKey: 'warehouse_name',
              title: '仓库简称',
              edit: {
                // 1. 支持任意组件。需保证组件包含 `value` 和 `onChange` 两个属性，且 onChange 的第一个参数值为 new value。
                // 2. 如果希望支持校验，组件还需包含 `status` 和 `tips` 属性。具体 API 含义参考 Input 组件
                component: Input,
                // props, 透传全部属性到 Input 组件
                props: {
                  // clearable: true,
                  // autofocus: true,
                  // autoWidth: true,
                  size: 'large',
                },
                // 校验规则，此处同 Form 表单
                rules: [
                  { required: true, message: '不能为空' },
                  { max: 100, message: '字符数量不能超过 100', type: 'warning' },
                ],
                showEditIcon: false,
              },
            },
            {
              align: 'left',
              width: 200,
              ellipsis: true,
              colKey: 'remark',
              title: '地址备注',
              edit: {
                // 1. 支持任意组件。需保证组件包含 `value` 和 `onChange` 两个属性，且 onChange 的第一个参数值为 new value。
                // 2. 如果希望支持校验，组件还需包含 `status` 和 `tips` 属性。具体 API 含义参考 Input 组件
                component: Input,
                // props, 透传全部属性到 Input 组件
                props: {
                  size: 'large',
                },
                // 校验规则，此处同 Form 表单
                rules: [
                  { required: true, message: '不能为空' },
                  { max: 100, message: '字符数量不能超过 100', type: 'warning' },
                ],
                showEditIcon: false,
              },
            },
            {
              align: 'left',
              width: 200,
              ellipsis: true,
              colKey: 'name',
              title: '联系人姓名',
              edit: {
                // 1. 支持任意组件。需保证组件包含 `value` 和 `onChange` 两个属性，且 onChange 的第一个参数值为 new value。
                // 2. 如果希望支持校验，组件还需包含 `status` 和 `tips` 属性。具体 API 含义参考 Input 组件
                component: Input,
                // props, 透传全部属性到 Input 组件
                props: {
                  size: 'large',
                },
                // 校验规则，此处同 Form 表单
                rules: [
                  { required: true, message: '不能为空' },
                  { max: 10, message: '字符数量不能超过 10', type: 'warning' },
                ],
                showEditIcon: false,
              },
            },
            {
              align: 'left',
              width: 200,
              ellipsis: true,
              colKey: 'phone',
              title: '联系电话',
              edit: {
                // 1. 支持任意组件。需保证组件包含 `value` 和 `onChange` 两个属性，且 onChange 的第一个参数值为 new value。
                // 2. 如果希望支持校验，组件还需包含 `status` 和 `tips` 属性。具体 API 含义参考 Input 组件
                component: Input,
                // props, 透传全部属性到 Input 组件
                props: {
                  // clearable: true,
                  size: 'large',
                },
                // 校验规则，此处同 Form 表单
                rules: [
                  { required: true, message: '不能为空' },
                  { max: 18, message: '字符数量不能超过 18', type: 'warning' },
                ],
                showEditIcon: false,
              },
            },
            {
              align: 'left',
              fixed: 'right',
              width: 220,
              colKey: 'op',
              title: '操作',
              cell: ({ row }) => {
                const editable = editableRowKeys.includes(row.id);
                return (
                  <>
                    {editable && (
                      <Button theme='primary' variant='text' data-id={row.id} onClick={onSave}>
                        确定
                      </Button>
                    )}
                    {editable && (
                      <Button theme='primary' variant='text' data-id={row.id} onClick={onCancel}>
                        取消
                      </Button>
                    )}
                    {!editable && (
                      <Button theme='primary' variant='text' data-id={row.id} onClick={onEdit}>
                        编辑
                      </Button>
                    )}
                    {!editable && (
                      <Button
                        theme='primary'
                        variant='text'
                        onClick={() => {
                          onDelete(row);
                        }}
                      >
                        删除
                      </Button>
                    )}
                    {!editable && (
                      <Button
                        theme='primary'
                        variant='text'
                        onClick={() => {
                          onUse(row);
                        }}
                      >
                        使用
                      </Button>
                    )}
                  </>
                );
              },
            },
          ]}
          loading={loading}
          ref={tableRef}
          rowKey='id'
          data={isEditing ? addressEditList : addressList}
          editableRowKeys={editableRowKeys}
          onRowEdit={onRowEdit}
          onRowValidate={onRowValidate}
          // selectedRowKeys={selectedRowKeys}
          verticalAlign='top'
          hover
          onSelectChange={onSelectChange}
          pagination={{
            pageSize: page_size,
            total,
            current: page_num,
            showJumper: true,
            onCurrentChange(current, pageInfo) {
              console.log(current, pageInfo);
              dispatch(
                getList({
                  page_size: pageInfo.pageSize,
                  page_num: pageInfo.current,
                }),
              );
            },
            onPageSizeChange(size) {
              dispatch(
                getList({
                  page_size: size,
                  page_num: 1,
                }),
              );
            },
          }}
        />
      </Dialog>
    );
  },
);
